package com.example.demo.delayQueue;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * LinkedBlockingQueue实现生产者消费者模型
 */
public class LinkedBlockingQueueTest {
    //LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<String>(3);
    private int i;
    LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<> ( 3 );

    class Producer implements Runnable {
        @Override
        public void run() {
            for (int j = 0; j < 10; j++) {
                try {
                    queue.put ( j );
                    //System.out.print("生产,,,,,,");
                    System.out.println ( "生产,,,,,,剩余容量：" + queue.remainingCapacity () );
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }

            }
        }
    }

    class Consumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Integer take = queue.take ();
                    Thread.sleep ( 2000 );
//                    System.out.println ( "消费,,,,剩余容量：" + queue.remainingCapacity () );
                    System.out.println ( "消费:" + take );
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        }
    }

    public static void main(String[] args) {
        LinkedBlockingQueueTest linkedBlockingQueueTest = new LinkedBlockingQueueTest ();
        linkedBlockingQueueTest.queue = new LinkedBlockingQueue<> ( 1024 );
        for (int i = 0; i < 2; i++) {
            linkedBlockingQueueTest.queue.add ( i );
        }
        new Thread ( linkedBlockingQueueTest.new Consumer () ).start ();
        for (int i = 0; i < 10; i++) {
            linkedBlockingQueueTest.queue.add ( i + 10 );
        }
    }
}
